//
//  BaseViewController.swift
//  
//
//  Created by tank on 2021/12/16.
//

import Foundation
import UIKit


open class InteractivePopDelegate: NSObject, UIGestureRecognizerDelegate {
    
    private weak var viewController: UIViewController?
    
    
    public init(viewController: UIViewController) {
        super.init()
        
        self.viewController = viewController
    }
    
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {

        return true
    }

    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {

        guard UIApplication.shared.statusBarOrientation == .portrait else {
            return false
        }

        return true
    }

    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {

        if gestureRecognizer == viewController?.navigationController?.interactivePopGestureRecognizer {
            return true
        }

        return false
    }
}


open class BaseViewController: UIViewController {

    private weak var originInteractivePopDelegate: UIGestureRecognizerDelegate?
    
    private lazy var interactivePopDelegate: InteractivePopDelegate = InteractivePopDelegate(viewController: self)

    private var interactivePop: Bool
    
    public init(nibName nibNameOrNil: String?,
                         bundle nibBundleOrNil: Bundle?,
                         interactivePop: Bool = true) {
        self.interactivePop = interactivePop
        
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    open override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        navigationController?.setNavigationBarHidden(true, animated: false)
    }

    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if interactivePop {
            originInteractivePopDelegate = navigationController?.interactivePopGestureRecognizer?.delegate
            navigationController?.interactivePopGestureRecognizer?.delegate = interactivePopDelegate
        } else {
            navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        }
    }

    open override func viewWillDisappear(_ animated: Bool) {

        super.viewWillDisappear(animated)

        UIWindow.ex.key?.endEditing(true)

        if interactivePop {
            navigationController?.interactivePopGestureRecognizer?.delegate = originInteractivePopDelegate
        } else {
            navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        }
    }
}
